package com.yingxue.lesson.sihro;

import com.yingxue.lesson.constant.Constant;
import com.yingxue.lesson.utils.JwtTokenUtil;
import com.yingxue.lesson.utils.RedisService;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

/**
 * @author chahua
 * @date 2022/4/5 17:09
 **/
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private RedisService redisService;

    /**
     * 设置支持令牌校验
     *
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomUsernamePasswordToken;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String accessToken = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Claims claims = JwtTokenUtil.getClaimsFromToken(accessToken);
        /**
         * 获取用户的角色信息给授权器
         */
        if(claims.get(Constant.ROLES_INFOS_KEY)!=null){
            simpleAuthorizationInfo.addRoles((Collection<String>) claims.get(Constant.ROLES_INFOS_KEY));
        }
        /**
         * 获取该用户的权限信息给授权器
         */
        if(claims.get(Constant.PERMISSIONS_INFOS_KEY)!=null){
            simpleAuthorizationInfo.addStringPermissions((Collection<String>) claims.get(Constant.PERMISSIONS_INFOS_KEY));
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authenticationToken;
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(token.getPrincipal(),token.getCredentials(),getName());
        return simpleAuthenticationInfo;
    }
}
